<template>
  <div class="userStore-container">
    <div class="store-info-container">
      <!-- 店铺信息卡片 -->
      <el-card class="store-info-card">
        <template #header>
          <div class="card-header">
            <h3>品牌信息</h3>
          </div>
        </template>
        <el-descriptions :column="1" border label-width="180px">
          <el-descriptions-item label="所属分类" label-class-name="el-descriptions-required">
            <el-select
              v-if="action !== 'view'"
              v-model="storeInfo.category_id"
              :class="{ 'is-error': errors.category_id }"
              multiple
            >
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <span v-else>
              {{ cateList.find((i) => i.id === storeInfo.category_id)?.name }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="品牌名称" label-class-name="el-descriptions-required">
            <el-input
              v-if="action !== 'view'"
              v-model="storeInfo.name"
              :class="{ 'is-error': errors.name }"
            />
            <span v-else>
              {{ storeInfo.name }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="公司名称">
            <el-input
              v-if="action !== 'view'"
              v-model="storeInfo.company_name"
            />
            <span v-else>
              {{ storeInfo.company_name }}
            </span>
          </el-descriptions-item>

          <el-descriptions-item label="品牌logo" label-class-name="el-descriptions-required">
            <el-upload
              v-if="action !== 'view'"
              v-model:file-list="fileList"
              ref="uploadRef"
              class="upload-demo"
              :action="uploadParams['host']"
              :before-upload="beforeUpload"
              :limit="1"
              :on-exceed="handleExceed"
              :data="uploadParams['param']"
              :on-success="handleSuccessBus"
              :on-error="handleError"
              :on-preview="handlePreview('logo_url')"
              :on-remove="handleRemoveBus"
              list-type="picture-card"
            >
              <el-icon><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">
                  支持jpg/png/webp格式，图片大小在10M内，建议上传图片尺寸1:1
                </div>
              </template>
            </el-upload>
            <el-image v-else :src="storeInfo.logo_url" class="logo_url-image" />
          </el-descriptions-item>
          <el-descriptions-item label="备注：">
            <el-input
              v-if="action !== 'view'"
              v-model="storeInfo.remark"
              placeholder="请输入备注"
              type="textarea"
              :rows="3"
            />
            <span v-else>{{ storeInfo.remark }}</span>
          </el-descriptions-item>
          <el-descriptions-item v-if="action === 'view'" label="审核状态：">
            <el-tag :type="statusName(storeInfo.status)?.type">
              {{ statusName(storeInfo.status)?.name }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item v-if="action === 'view'" label="审核备注：">
            <span>{{ storeInfo.status_remark }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <div class="button-container">
        <el-button @click="handleReturn">返回</el-button>
        <el-button
          v-if="action === 'add'"
          v-repeat
          type="primary"
          @click="handleSubmit"
        >
          提交
        </el-button>
        <el-button
          v-if="action === 'edit'"
          v-repeat
          type="primary"
          @click="handleSubmit"
        >
          修改
        </el-button>
      </div>
    </div>

    <!-- 添加图片预览组件 -->
    <el-image-viewer
      v-if="showViewer"
      :url-list="[previewUrl]"
      :hide-on-click-modal="true"
      @close="showViewer = false"
    />
  </div>
</template>

<script lang="ts">
  export default {
    name: 'brandAdd',
  }
</script>

<script lang="ts" setup>
  import { ref, reactive, computed } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { ElMessage, genFileId } from 'element-plus'
  import { getOSSParam } from '@/api/common'
  import { getcateList } from '@/api/goods'
  import {
    supplierApplyBrandAdd as addBrand,
    getBrandApplyInfo as getBrandInfo,
  } from '@/api/brand'
  import { message } from '@/utils/helper'
  const router: any = useRouter()
  const route: any = useRoute()
  const action = ref(route.query.action || 'view')

  // 添加校验规则
  const rules = {
    category_id: { required: true, message: '请选择分类' },
    name: { required: true, message: '请输入品牌名称' },
    logo_url: { required: true, message: '请上传品牌logo_url' },
  }
  const statusName: any = computed(() => {
    return (status) => {
      switch (status) {
        case 1:
          return { name: '待审核', type: 'primary' }
        case 2:
          return { name: '审核通过', type: 'success' }
        case 3:
          return { name: '审核不通过', type: 'danger' }
      }
    }
  })
  // 错误状态
  const errors = reactive({
    category_id: false,
    name: false,
    logo_url: false,
  })
  const fileList = ref([])
  // 店铺信息数据
  const storeInfo: any = reactive({
    id: undefined,
    category_id: undefined,
    name: '',
    company_name: '',
    logo_url: '',
    status: undefined,
    remark: '',
    status_remark: '',
  })

  // 返回按钮处理函数
  const handleReturn = () => {
    Object.assign(storeInfo, {
      id: undefined,
      category_id: [],
      name: '',
      company_name: '',
      logo_url: '',
      status: undefined,
      remark: '',
      status_remark: '',
    })
    fileList.value = []
    router.push({ path: '/brand/brandApplyForAdmin', query: { repalce: true } })
  }

  const CheckRulesEmpty = () => {
    let isValid = true
    let firstErrorField = ''

    // 重置所有错误状态
    Object.keys(errors).forEach((key) => {
      errors[key] = false
    })

    // 检查每个必填字段
    Object.keys(rules).forEach((key) => {
      if (!storeInfo[key]) {
        errors[key] = true
        isValid = false
        if (!firstErrorField) {
          firstErrorField = rules[key].message
        }
      }
    })

    if (!isValid) {
      ElMessage.error(firstErrorField)
    }

    return isValid
  }

  const handleSubmit = async () => {
    if (CheckRulesEmpty()) {
      console.log(storeInfo)
      // 这里添加提交逻辑
      if (action.value === 'add') {
        await addBrand({
          ...storeInfo,
          category_id: storeInfo.category_id.join(','),
        })
      } else {
        await addBrand({
          ...storeInfo,
          category_id: storeInfo.category_id.join(','),
        })
      }
      message('更新成功')
      handleReturn()
    }
  }

  const uploadParams: globalItem = ref({
    host: '',
    param: {},
    dir: '',
  })

  const uploadRef = ref(null)
  const image_list = ref(['image/png', 'image/jpeg', 'image/webp'])
  const uploadLoading = ref(false)
  const beforeUpload = (rawFile) => {
    if (image_list.value.includes(rawFile.type)) {
      if (rawFile.size / 1024 / 1024 > 10) {
        ElMessage.error('上传的图片不得大于10M!')
        return false
      }
      const image_type = rawFile.type.split('/')[1]
      uploadParams.value.param.key = `${uploadParams.value.dir}/${rawFile.uid}.${image_type}`
      uploadLoading.value = true
      return true
    } else {
      ElMessage.error('上传的图片不是图片(jpg,png,webp)类型')
      return false
    }
  }
  const handleExceed = (files) => {
    uploadRef.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadRef.value.handleStart(file)
    uploadRef.value.submit()
  }

  const handleSuccessBus = async () => {
    storeInfo.logo_url = `${uploadParams.value.host}/${uploadParams.value.param.key}`
    uploadLoading.value = false
  }

  const handleError = (err) => {
    ElMessage.error('上传简历失败, 请尝试重新上传')
    getOSSParams()
    uploadLoading.value = false
  }

  // 预览相关变量
  const showViewer = ref(false)
  const previewUrl = ref('')
  const handleRemoveBus: any = () => {
    storeInfo.logo_url = ''
    fileList.value = []
  }
  // 修改预览处理函数
  const handlePreview = (key: string) => (file: any) => {
    if (file.url) {
      previewUrl.value = file.url
    } else {
      previewUrl.value = storeInfo[key]
    }
    showViewer.value = true
  }

  const getOSSParams = async () => {
    const { data } = await getOSSParam()
    uploadParams.value = data
  }
  const cateList = ref([])
  const getCateList = async () => {
    const { data } = await getcateList({
      limit: 1000,
    })
    cateList.value = data.data
  }
  const getBrandInfoData = async (id) => {
    const { data } = await getBrandInfo({ id })
    //根据storeInfo的key，将data的值赋值给storeInfo
    Object.keys(storeInfo).forEach((key) => {
      storeInfo[key] = data[key]
    })
    storeInfo.category_id = storeInfo.category_id.split(',').map(Number)
    fileList.value = storeInfo.logo_url ? [{ url: storeInfo.logo_url }] : []
    console.log(storeInfo)
  }
  onMounted(() => {
    getOSSParams()
    getCateList()
    if (route.query.id) {
      getBrandInfoData(route.query.id)
    }
  })
</script>
<style scoped></style>

<style lang="scss" scoped>
  .is-error {
    :deep(.el-input__wrapper) {
      border: 1px solid #f56c6c;
      &:focus {
        border: 1px solid #1890ff;
      }
    }
  }
  .store-info-container {
    padding: 20px;

    .store-info-card,
    .audit-result-card {
      margin-bottom: 20px;

      .card-header {
        h3 {
          margin: 0;
          color: #303133;
        }
      }
    }

    .license-image,
    .logo_url-image {
      width: 200px;
      height: 100px;
      object-fit: contain;
    }

    .button-container {
      text-align: center;
      margin-top: 20px;
    }
  }

  :deep(.el-descriptions__label) {
    width: 120px;
    text-align: right;
    font-weight: bold;
  }
  .set-address {
    cursor: pointer;
    color: #7aa9f7;
    border-bottom: 1px solid #7aa9f7;
  }

  // 添加预览相关样式
  :deep(.el-image-viewer__wrapper) {
    .el-image-viewer__close {
      color: #fff;
    }
  }

  .el-image {
    cursor: pointer;
  }

  :deep(.el-card.is-always-shadow) {
    box-shadow: none !important;
  }
  :deep(.el-card) {
    border: none !important;
  }
</style>
